package control;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import swimv2.ejb.remote.GestioneUtentiRemote;
import swimv2.ejb.util.LoginToken;

public class GestioneUtentiServlet extends Servlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private void getFotoProfilo(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session=request.getSession();
		try {
			Context jndiContext = new javax.naming.InitialContext();
			Object ref2 = jndiContext.lookup("GestioneUtenti/remote");
			GestioneUtentiRemote gestioneUtentiRemote = (GestioneUtentiRemote) PortableRemoteObject.narrow(ref2, GestioneUtentiRemote.class);
			
			LoginToken tok=(LoginToken) session.getAttribute("LoginToken");
			String username=tok.getUsername();
			byte[] fotoProfilo = gestioneUtentiRemote.getFotoProfilo(username);
			
			response.setContentType("image/png");
			response.setContentLength(fotoProfilo.length);
			response.getOutputStream().write(fotoProfilo);
		}
		catch(NamingException e) {
			e.printStackTrace();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}
	
	@Override
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		
		//String to=(String) request.getParameter("to");
    	//if(to.equals("getFotoProfilo"))
    		this.getFotoProfilo(request, response);
    	
	}

}
